import { createAxios } from '@/utils/http/axios';
import { getToken } from '@/utils/auth';

enum Api {
  selectIotUniDataLog = '//data/iotUniDataLog/selectList',
  // getHistoryData = '/tbuser/deviceDataQuery/getHistoryData',
  // getOriginalDataBySn = '/tbuser/deviceDataQuery/getOriginalDataBySn',
  exportDeviceHistoryData = '/tbuser/deviceDataQuery/exportDeviceHistoryData',
}

export function exportDeviceHistoryDataApi(data: {
  sn: string;
  startTs: number;
  endTs: number;
  fileType?: 'xlsx';
}) {
  const token = getToken();
  const headers = new Headers();
  headers.append('Content-Type', 'application/json;charset=UTF-8');
  headers.append('Authorization', token);
  fetch('/hc-api' + Api.exportDeviceHistoryData, {
    method: 'POST',
    body: JSON.stringify({
      sn: data.sn,
      startTs: data.startTs, //开始时间
      endTs: data.endTs, //结束时间
      fileType: data.fileType,
    }),
    headers,
  })
    .then(function (response: Response) {
      return response.blob();
    })
    .then(function (blob) {
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob);
      document.body.appendChild(link);
      link.click();
      // 释放的 URL 对象以及移除 a 标签
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    });
}

export interface IotUniDataLog {
  id: string;

  ts: number;

  deviceInfo: {
    imei: string;
    productKey: string;
  };

  /**
   * 协议版本
   */
  protocolKey: string;

  /**
   * 设备编码
   */
  sn: string;

  /**
   * 功能
   */
  func: string;

  action: string;

  topic: string;

  contentType: string;

  contents: [];

  paramMap: {};

  raw: {
    contentType: string;
    contents: [];
    protocolKey: string;
  };
}

// export interface OriginalData {
//   ts: number;
//   rawStr: string;
//   sourceType: string;
// }

// export function getOriginalDataBySnApi(data: {
//   sn: string;
//   startTs: number;
//   endTs: number;
//   sourceType: string;
// }): Promise<IotUniDataLog[]> {
//   return createAxios({
//     requestOptions: {
//       apiUrl: '/hc-api',
//       // withToken: false,
//     },
//   }).post({
//     url: Api.getOriginalDataBySn,
//     data,
//   });
// }

// export function getHistoryDataApi(data: { sn: string; startTs: number; endTs: number }) {
//   return createAxios({
//     requestOptions: {
//       apiUrl: '/hc-api',
//       // withToken: false,
//     },
//   }).post({
//     url: Api.getHistoryData,
//     data,
//   });
// }

export function selectIotUniDataLogApi(data: {
  sn: string;
  func: string;
  action: string;
  includeFields: string[];
  startTs: number;
  endTs: number;
}): Promise<IotUniDataLog[]> {
  return createAxios({
    requestOptions: {
      apiUrl: '/hc-api',
      // withToken: false,
    },
  }).post({
    url: Api.selectIotUniDataLog,
    data,
  });
}
